import time

# from .common import CommonTaobao
from common.db import get_db
from common.db.crud import taobao as taobao_crud
from tasks.taobao.common import CommonTaobao


class ChangeAccount(CommonTaobao):

    def __init__(self, android_ip):
        super().__init__(android_ip)
        self.user_phone = self.order.user_phone
        self.user_name = self.order.user_name
        self.password = self.order.password

    @property
    def analysis_dict(self):
        return {
            '更多': ['返回', '更多', "头像"],
            '弹出换个账号登录': ['换个账号登录', '注册', '遇到问题？', '取消'],
            '换个账号登录': ['切换账号登录', '换个账号登录'],
            '换个账户登录': ['换个账户登录'],
            '亲，欢迎登录': [['没有淘宝账号？', '没有淘宝账户？'], '立即注册', '确认'],
            '输入登录密码': ['亲，欢迎登录', '密码已隐藏', '登录', '忘记密码'],
            '下方弹出登录方式': ['扫脸登录', '账号密码登录', '取消'],
            '更多登录方式': ['更多登录方式', '亲，欢迎登录'],
            '账号密码登录': ['亲，欢迎登录', '账号密码登录', '获取验证码'],
            '账户密码登录': ['亲，欢迎登录', '账户密码登录', '获取验证码'],
            '弹出请选择其它登录方式': ['请选择其它登录方式', '账号密码登录', '短信验证码登录', '取消'],
            '服务协议及隐私保护': ['不同意', '同意'],
            '首页': ['首页', '消息', '购物车', '我的淘宝'],
            '身份验证-校验码': ['身份验证', '下一步', '遇到问题？', '获取短信校验码'],
            '身份验证-验证码': ['身份验证', '下一步', '遇到问题？', '获取验证码'],
            '切换账户登录': ['轻触账户以登录', '当前登录', '换个账户登录', '删除此设备上的账户记录']
        }

    def input_phone_code(self):
        self.log_msg("即将通过接口获取验证码")
        code = self.get_code()
        self.log_msg('即将输入{}的短信校验码={}'.format(self.user_phone, code))
        time.sleep(1)
        self.u2.set_input_text(code)
        self.log_msg('即将点击下一步')
        time.sleep(1)
        self.click_text('下一步')

    def check_is_login(self, click_text):
        index = self.current_page_only_text.index('当前登录')
        login_user = self.current_page_only_text[index - 1]
        self.log_msg("当前登录账号为 {}".format(login_user))
        user_list = login_user.split('*')
        start, end = user_list[0], user_list[-1]

        def check_start_and_end(name: str):
            if name.startswith(start) and name.endswith(end):
                return True

        if check_start_and_end(self.user_name):
            self.log_msg("当前账号 {} = 订单账号{}, 现在回到首页".format(login_user, self.user_name))
            self.u2.start_activity("com.taobao.taobao", 'com.taobao.tao.TBMainActivity')
            return True
        else:
            self.log_msg("当前账号 {} != 订单账号{}, 点击切换账号".format(login_user, self.user_name))
            self.click_text(click_text)
            return False

    def login(self):
        self.u2.start_activity("com.taobao.taobao", 'com.taobao.tao.TBMainActivity')
        time.sleep(3)
        self.adb.open_activity('com.taobao.taobao',
                               'com.taobao.login4android.membercenter.account.MultiAccountActivity')
        time.sleep(1)
        err_count = 0
        while True:
            current = self.what_current_page()
            # 记录连续出问题
            err_count = 0 if current else err_count + 1
            if current == '更多':
                self.click_text('更多')
            elif current in ['换个账号登录', '弹出换个账号登录']:
                if self.check_is_login('换个账号登录'):
                    self.log_msg("账号登录成功，退出账号切换流程")
                    break
                else:
                    self.log_msg("进入账号切换流程")
            elif current in ['换个账户登录', '切换账户登录']:
                if self.check_is_login('换个账户登录'):
                    self.log_msg("账号登录成功，退出账号切换流程")
                    break
                else:
                    self.log_msg("进入账号切换流程")
            elif current == '亲，欢迎登录':
                self.log_msg("即将 点击同意使用协议")
                self.u2.click_resource_id("com.taobao.taobao:id/aliuser_reg_checkbox")
                self.log_msg("即将 切换输入法")
                self.u2.d.set_fastinput_ime()
                time.sleep(0.5)
                self.log_msg("即将 点击账号用户输入框")
                self.u2.click_resource_id("com.taobao.taobao:id/aliuser_recommend_login_account_rl")
                time.sleep(0.5)
                self.log_msg("即将 输入用户名")
                self.u2.d.send_keys(self.order.user_name, clear=True)
                time.sleep(0.5)
                self.log_msg("输入用户名后，就能点击确认，即将点击")
                self.u2.click_resource_id("com.taobao.taobao:id/aliuser_recommend_login_next_btn")
            elif current == '服务协议及隐私保护':
                self.log_msg('即将点击 服务协议及隐私保护的同意')
                self.click_text('同意')
            elif current == '更多登录方式':
                self.log_msg('即将点击更多登录方式')
                self.click_text('更多登录方式')
            elif current == '账号密码登录':
                self.log_msg('即将点击账户密码登录')
                self.click_text('账号密码登录')
            elif current == '账户密码登录':
                self.log_msg('即将点击账户密码登录')
                self.click_text('账户密码登录')
            elif current == '弹出请选择其它登录方式':
                self.log_msg('即将点击账号密码登录')
                self.click_text('账号密码登录')
            elif current == '下方弹出登录方式':
                self.log_msg('即将点击账户密码登录')
                self.click_text('账号密码登录')
            elif current == '输入登录密码':
                time.sleep(0.5)
                self.log_msg("即将点击密码输入框")
                self.u2.d(resourceId="com.taobao.taobao:id/aliuser_recommend_login_password_rl").click()
                time.sleep(0.5)
                self.log_msg("即将 输入密码")
                self.u2.d.send_keys(self.order.password, clear=True)
                time.sleep(0.5)
                self.log_msg("用户名密码都输入了，即将点击确认登陆")
                self.u2.click_resource_id("com.taobao.taobao:id/aliuser_recommend_login_next_btn")
                self.log_msg("将已经点击过登录，改为True")
                time.sleep(2)
            elif current == '首页':
                self.adb.open_activity('com.taobao.taobao',
                                       'com.taobao.login4android.membercenter.account.MultiAccountActivity')
            elif '身份验证-校验码' == current:
                self.click_text("获取短信校验码")
                self.input_phone_code()
            elif '身份验证-验证码' == current:
                self.click_text("获取验证码")
                self.input_phone_code()
            else:
                self.log_msg('第{}次无法识别当前页面'.format(err_count))
                if err_count >= 3:
                    self.raise_exception("in login, can't identify current page, exit -1")
                else:
                    self.log_msg('再次尝试识别当前页面')
                    time.sleep(3)

    def start(self):
        self.log_msg('need change account to user={}'.format(self.order.user_phone))
        self.login()


class BuyProduct(CommonTaobao):

    def __init__(self, android_ip):
        super().__init__(android_ip)
        self.product_url = self.order.shop_url

    @property
    def analysis_dict(self):
        return {
            '免密支付失败': ['添加银行卡付款', '找朋友帮忙付'],
            '确认订单': ['确认订单', '订单备注', '提交订单'],
            '支付成功': ['支付成功', '返回首页'],
            '商品选择': ['商品图', '关闭', '￥'],
            '立即付款': ['立即付款', '支付宝账号', '退出', '付款方式'],
            '确认付款': ['支付宝账号', '账户余额', '确认付款', '本服务由支付宝(中国)网络技术有限公司提供'],
            '请输入支付密码': ['取消', '确定', '请输入支付密码'],
            '请输入数字支付密码': ['取消', '请输入支付密码'],
            '身份验证': ['校验码', '身份验证', '填写校验码', '下一步'],
            '支付密码不正确': ['请输入支付密码？', '取消', '确定:', '支付密码不正确'],
        }

    def get_pay_complete_flag(self):
        self.order = taobao_crud.get_order(next(get_db()), self.android_ip)
        return self.order.complete

    def update_db_order_number(self, order_number):
        taobao_crud.update_order(next(get_db()), self.android_ip, dict(order_number=order_number))

    def input_phone_code(self):
        self.log_msg("即将通过接口获取验证码")
        code = self.get_code()
        self.log_msg('即将输入{}的短信校验码={}'.format(self.order.user_phone, code))
        time.sleep(1)
        self.u2.set_input_text(code)
        self.log_msg('即将点击下一步')
        time.sleep(1)
        self.click_text('下一步')

    def buy_and_pay(self):
        self.log_msg("即将进入淘宝主页")
        self.u2.start_activity("com.taobao.taobao", 'com.taobao.tao.TBMainActivity')
        time.sleep(0.5)
        self.log_msg("即将打开淘宝商品连接")
        self.adb.open_activity_with_url("com.taobao.taobao",
                                        "com.taobao.browser.BrowserActivity", self.order.shop_url)
        time.sleep(0.5)
        self.log_msg("即将点击立即购买按钮")
        time.sleep(0.5)
        self.u2.click_text("立即购买")

        def confirm_order():
            self.log_msg("即将点击提交订单按钮")
            self.u2.click_text("提交订单")
            time.sleep(5)

        def choose_product():
            if not self.order.sub_name:
                self.raise_exception('Currently on the product selection page, '
                                     'but the api interface has no sub-item attributes')
            else:
                self.log_msg("需要点选子类目为={}".format(self.order.sub_name))
                if not self.u2.check_text_is_exist(self.order.sub_name):
                    self.raise_exception("There is no product subcategory name={}".format(self.order.sub_name))
                self.u2.click_text(self.order.sub_name)
                self.log_msg("选好子商品后即将点击确认")
                self.u2.click_text('确认')
                confirm_order()

        err_count = 0
        while True:
            current = self.what_current_page()
            # 记录连续出问题
            err_count = 0 if current else err_count + 1
            if current == '商品选择':
                choose_product()
            elif current == '确认订单':
                confirm_order()
            elif current == '支付成功':
                self.log_msg('当前处于支付成功页面，结束')
                taobao_crud.update_order(self.db_session, self.android_ip, dict(complete=True))
                break
            elif current == '免密支付失败':
                pass
            elif current == '全部订单':
                self.log_msg("即将点击第一个出现的'{}'".format(self.order.shop_name))
                self.click_first_text(self.order.shop_name)
            elif '立即付款' == current:
                self.log_msg("即将点击立即付款按钮")
                self.click_text("立即付款")
            elif '确认付款' == current:
                self.log_msg("即将点击确认付款按钮")
                self.click_text("确认付款")
            elif '请输入支付密码' == current:
                self.log_msg("即将输入字母类型的付款密码")
                time.sleep(1)
                self.adb.input_text(self.order.payment_password)
                self.log_msg("即将点击输入支付密码后的确定按钮")
                self.u2.click_text("确定")
            elif current == '请输入数字支付密码':
                self.log_msg("即将输入纯数字的付款密码")
                time.sleep(1)
                self.adb.input_text(self.order.payment_password)
            elif '身份验证' == current:
                self.input_phone_code()
            elif '支付密码不正确' == current:
                self.raise_exception("payment password is incorrect, please check")
            else:
                self.log_msg('第{}次无法识别当前页面'.format(err_count))
                if err_count >= 3:
                    msg = 'During the purchase of goods, the current page cannot be recognized and exits abnormally'
                    self.raise_exception(msg)
                else:
                    self.log_msg('再次尝试识别当前页面')
                    time.sleep(3)

    def start(self):
        if self.get_pay_complete_flag():
            self.log_msg('订单已经付款过，直接去复制订单编号')
            CopyOrderNumber(self.android_ip).run()
        else:
            self.log_msg('开始全新的订单')
            self.buy_and_pay()
            CopyOrderNumber(self.android_ip).run()


class CopyOrderNumber(CommonTaobao):
    def __init__(self, uuid):
        super().__init__(uuid)

    @property
    def analysis_dict(self):
        return {
            '全部订单': ['全部', '待付款', '待发货', '待收货', '待评价'],
            '订单详情': ['实付款', '订单编号:', '复制'],
        }

    def goto_all_order(self):
        self.log_msg('即将跳转全部订单页')
        self.goto_main_activity(delay_time=3)
        self.adb.open_activity('com.taobao.taobao', 'com.taobao.android.order.bundle.TBOrderListActivity')
        time.sleep(1)

    def get_order_number(self):
        self.goto_all_order()
        err_count = 0
        while True:
            current = self.what_current_page()
            # 记录连续出问题
            err_count = 0 if current else err_count + 1
            if current == '订单详情':
                page_value = self.get_current_page_xml()
                page_text_list = [i['only_text'] for i in page_value]
                index = page_text_list.index('订单编号:')
                order_number = page_text_list[index + 1].strip()
                self.log_msg('order_number={}'.format(order_number))
                taobao_crud.update_order(self.db_session, self.android_ip, dict(order_number=order_number))
                break
            elif current == '全部订单':
                self.log_msg("即将点击第一个出现的'{}'".format(self.order.shop_name))
                self.click_first_text(self.order.shop_name)
            else:
                self.log_msg("can't identify current page No.{} time".format(err_count))
                if err_count >= 3:
                    self.raise_exception("In copy order number, can't identify current page, "
                                         "current_text={}, exit -1".format(self.current_page_only_text))
                else:
                    self.log_msg('identify current page again')
                    time.sleep(3)

    def run(self):
        self.order = taobao_crud.get_order(next(get_db()), self.android_ip)
        if not self.order.order_number:
            self.unlock_phone()
            self.log_msg('start get order number')
            return self.get_order_number()
